importJar("org.slf4j:slf4j-api:jar:1.7.21");
importJar("org.slf4j:slf4j-simple:jar:1.7.21");
importJar('org.slf4j:log4j-over-slf4j:jar:1.7.21');
importJar('org.javassist:javassist:jar:3.18.1-GA');
importJar('com.101tec:zkclient:jar:0.9');
importJar('org.apache.zookeeper:zookeeper:jar:3.4.6');
importJar('io.netty:netty:jar:3.7.0.Final');
importJar('com.alibaba:dubbo:jar:2.5.3');

importClass("com.alibaba.dubbo.config.ApplicationConfig");
importClass("com.alibaba.dubbo.config.ReferenceConfig");
importClass("com.alibaba.dubbo.config.RegistryConfig");
importClass("com.alibaba.dubbo.config.utils.ReferenceConfigCache");
importClass("com.alibaba.dubbo.rpc.service.GenericService");

// 创建dubbo上下文.
function Dubbo (address, protocol, applicationName) {
    this.applicationName = applicationName;
    this.address = address;
    if (null == this.address) {
        throw "param address null";
    }
    if (null == this.applicationName) {
        // 默认使用这个名称.
        this.applicationName = "dubbo-script-test-runner";
    }
    // 普通编码配置方式
    this.application = new ApplicationConfig();
    this.application.setName(this.applicationName);
    // 连接注册中心配置
    this.registry = new RegistryConfig();

    if (!protocol) {
        protocol = "zookeeper";
    }
    this.registry.setProtocol(protocol);
    this.registry.setAddress(this.address);
    // 不缓存zk连接配置.
    this.registry.setFile("N/A");
    this.application.setRegistry(this.registry);

    // 生成调用服务.
    this.service = function (serviceName, version, timeout) {
        var reference = new ReferenceConfig();
        // 指定上下文.
        reference.setApplication(this.application);
        // 指定配置.
        reference.setGeneric(serviceName);
        reference.setInterface(serviceName);
        if (version) {
            reference.setVersion(version);
        }
        if (timeout) {
            reference.setTimeout(timeout);
        }
        // 声明为泛化接口
        reference.setGeneric(true);
        var serviceInstance = reference.get();
        // 使用代理对象, 用于获取数据.
        return {
            invoke: function (methodName, parameterTypes, parameterValues) {
                return serviceInstance.$invoke(methodName, parameterTypes, parameterValues);
            },
            toString: function () {
                return serviceName + (null != version ? ":" + version : "");
            }
        };
    };
}
